// import qs from 'qs';
import {API_ROOT} from '../config'
import axios from 'axios'

axios.defaults.baseURL = API_ROOT
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.headers.post['Access-Control-Allow-Origin'] = '*/*'
axios.defaults.withCredentials = true
axios.defaults.headers['Authorization'] = '8fdfc93c-e5f2-46e3-99b7-ff8718529449'

export default {
  // get请求
  get (url, param) {
    // 注释原因：mdParam只允许在post请求传输
    // let mdParam = window.Qs.parse(sessionStorage.getItem(Vue.prototype.route.path + '/mdParam'));
    let params = {
      ...param
      // ...mdParam
    }
    return new Promise((resolve, reject) => {
      axios({
        method: 'get',
        url: url,
        params: params
      }).then(res => {
        resolve(res)
      }).catch(e => {
        reject(e)
      })
    })
  },
  // post请求
  post (url, param, config) {
    let params = {
      ...param
    }
    return new Promise((resolve, reject) => {
      axios({
        method: 'post',
        headers: {
          ...config
        },
        data: params,
        url: url
      }).then(res => {
        resolve(res)
      }).catch(e => {
        reject(e)
      })
    })
  },
  // post请求
  put (url, param, config) {
    let params = {
      ...param
    }
    return new Promise((resolve, reject) => {
      axios({
        method: 'put',
        headers: {
          ...config
        },
        data: params,
        url: url
      }).then(res => {
        resolve(res)
      }).catch(e => {
        reject(e)
      })
    })
  },
  formPost (url, params) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'post',
        url: url,
        data: params,
        headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
        withCredentials: true,
        transformRequest: [
          function (data) {
            let ret = ''
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            ret = ret.substring(0, ret.lastIndexOf('&'))
            return ret
          }
        ]
      }).then(res => {
        resolve(res)
      }).catch(e => {
        reject(e)
      })
    })
  },
  filePost (url, params) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'post',
        url: url,
        data: params,
        headers: {'Content-Type': 'multipart/form-data'},
        withCredentials: true
      }).then(res => {
        resolve(res)
      }).catch(e => {
        reject(e)
      })
    })
  },
  baseURL: API_ROOT
}
